package edu.stthomas.seis752.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import edu.stthomas.seis752.form.UserForm;

@Component
public class UserValidator implements Validator {

	public boolean supports(Class candidate) {
        return UserForm.class.isAssignableFrom(candidate);
    }

    public void validate(Object obj, Errors errors) {
    	System.out.println("object in validator: " + obj);
    	UserForm form = (UserForm)obj;
    	ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstname.required", "First name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastname.required", "Last name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "username.required", "User name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required", "Password is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "confirmpassword.required", "Confirm password is required.");
        if("0".equals(form.getFavoriteLocation())){
        	errors.rejectValue("favoriteLocation", "choose.location", "Location must be chosen");
        }
        if(!errors.hasErrors()){
        	if(!form.getConfirmPassword().equals(form.getPassword())){
            	errors.rejectValue("password", "passwords.notmatch", "Passwords do not match");
            }
        }
    }

}
